# -*- coding: utf_8 -*-  
import sys  
import logging  
import threading  
import modbus_tk  
import modbus_tk.defines as cst  
import modbus_tk.modbus as modbus  
import modbus_tk.modbus_rtu as modbus_rtu  
import serial  
import time
logger = modbus_tk.utils.create_logger(name="console", record_format="%(message)s")  
# 创建server  
server = modbus_rtu.RtuServer(serial.Serial("com4", 9600))  
slaver = server.add_slave(1)  

def setup():       
    slaver.add_block("coil", cst.HOLDING_REGISTERS, 0, 16)  
    slaver.set_values("coil", 0, (20,16,30,100,))  


def loop():  
    logger.info("running...")  
    # 启动从机  
    server.start()  
    while True:  
        # values = slaver.get_values("coil", 0, 8)  
        # #print values[0]  
        # if values:
        # 	print(values)
         
        # # 必要的延时  
        time.sleep(0.5)  

def destory():  
    logger.info("destory")     

    # 停止从机  
    server.stop()  

if __name__ == '__main__':
  	setup()
  	try:
  		loop()
  	except KeyboardInterrupt:
  		destory()